package com.basic.common.core.redis;

import com.basic.common.config.BasicConfig;
import com.basic.common.utils.StringUtils;
import io.jsonwebtoken.lang.Assert;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 添加redis前缀
 *
 * @author zhaoxy_jn@163.com
 */
@Component
public class RedisKeySerializer implements RedisSerializer<String>
{
    @Resource
    private BasicConfig config;

    private final Charset charset;

    public RedisKeySerializer()
    {
        this(StandardCharsets.UTF_8);
    }

    public RedisKeySerializer(Charset charset)
    {
        Assert.notNull(charset, "字符集不允许为NULL");
        this.charset = charset;
    }

    @Override
    public byte[] serialize(String string) throws SerializationException
    {
        // 通过项目名称basic.name来定义Redis前缀，用于区分项目缓存
        if (StringUtils.isNotEmpty(config.getName()))
        {
            return (config.getName() + ":" + string).getBytes(charset);
        }
        return string.getBytes(charset);
    }

    @Override
    public String deserialize(byte[] bytes) throws SerializationException
    {
        if (bytes == null) {
            return null;
        }
        String key = new String(bytes, charset);
        // 如果键值包含前缀，则去除前缀
        if (StringUtils.isNotEmpty(config.getName()) && key.startsWith(config.getName() + ":"))
        {
            return key.substring(config.getName().length() + 1);
        }
        return key;
    }
}
